<?php

namespace app\common\service\learn;

use app\common\enums\CourseTypeEnum;
use app\common\enums\QuestionTypeEnum;
use app\common\service\ApiService;
use app\common\model\banxi\learn\LearnHearingRecord;
use app\common\model\banxi\course\Course;
use app\common\model\banxi\course\CourseSection;
use app\common\model\banxi\course\CourseQuestion;
use app\common\model\banxi\learn\LearnHearingAnswerRecord;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

class LearnHearingService extends ApiService
{

    /**
     * 开始答题
     *
     * @param int $courseId 课程ID
     * @param string $accountId 账户ID
     * @param string $accountType 账户类型
     * @param string $accountOrganizationId 账户机构ID
     * @param int|null $skRecordId 上课记录ID
     * @param int|null $tutorTrainerId 辅导教练ID
     * @return array
     */
    public function startHearing($courseId, $accountId, $accountType, $accountOrganizationId, $skRecordId, $tutorTrainerId)
    {
        // 开启事务
        Db::startTrans();
        try {

            // 获取课程信息
            $CourseModel = new Course();
            $course = $CourseModel->find($courseId);

            if (!$course) {
                throw new ValidateException("开始答题失败，课程不存在");
            }
            // 验证课程类型是否为听力课程
            if ($course['courseType'] != CourseTypeEnum::HEARING) { // 超级听力
                throw new ValidateException("开始答题失败，课程不存在");
            }
            // 获取课程章节
            $CourseSectionModel = new CourseSection();
            $courseSections = $CourseSectionModel->listByCourse($courseId);
            if (!$courseSections) {
                throw new ValidateException("开始答题失败，课程内容未配置");
            }
            // 获取课程题目
            $CourseQuestionModel = new CourseQuestion();
            $questionList = $CourseQuestionModel->listByCourse($courseId);
            if (empty($questionList)) {
                throw new ValidateException("开始答题失败，课程内容未配置");
            }
//            halt($questionList);
            // 创建听力记录
            $learnHearingRecord = [
                'skRecordId' => $skRecordId,
                'accountId' => $accountId,
                'accountType' => $accountType,
                'accountOrganizationId' => $accountOrganizationId,
                'tutorTrainerId' => $tutorTrainerId,
                'studentId' => ($accountType == 'STUDENT') ? intval($accountId) : null,
                'trainerId' => ($accountType == 'TRAINER') ? intval($accountId) : null,
                'isSubmit' => false,
                'courseId' => $courseId,
                'courseName' => $course['name'],
                'answerDuration' => $course['answerDuration'],
                'passRate' => $course['passRate'],
                'listenFile' => $course['listenFile'],
                'answerStartTime' => date('Y-m-d H:i:s')
            ];

            // 保存听力记录
            $LearnHearingRecordModel = new LearnHearingRecord();
            $recordId = $LearnHearingRecordModel->insertGetId($learnHearingRecord);

            // 构建听力答题记录列表
            $learnHearingAnswerRecordList = [];
            foreach ($questionList as $it) {
                $section = null;
                foreach ($courseSections as $s) {
                    if ($s['id'] == $it['dataId']) {
                        $section = $s;
                        break;
                    }
                }

                if (empty($section)) {
                    continue;
                }

                $learnHearingAnswerRecord = [
                    'recordId' => $recordId,
                    'studentId' => ($accountType == 'STUDENT') ? intval($accountId) : null,
                    'trainerId' => ($accountType == 'TRAINER') ? intval($accountId) : null,
                    'courseId' => $courseId,
                    'sectionId' => $section['id'],
                    'sectionName' => $section['name'],
                    'questionId' => $it['id'],
                    'questionName' => $it['name'],
                    'questionType' => $it['questionType'],
                    'option' => $it['option'] ?? null,
                    'answer' => $it['answer'] ?? null,
                    'analysis' => $it['analysis'] ?? null,
                ];

                $learnHearingAnswerRecordList[] = $learnHearingAnswerRecord;
            }

            // 批量保存题目记录
            if (!empty($learnHearingAnswerRecordList)) {
                $LearnHearingAnswerRecordModel = new LearnHearingAnswerRecord();
                $LearnHearingAnswerRecordCollection = $LearnHearingAnswerRecordModel->saveAll($learnHearingAnswerRecordList);
            }

            // 构造返回结果
            $answerList = [];
            foreach ($LearnHearingAnswerRecordCollection as $item) {
                $question = [
                    'id' => $item['id'],
                    'sectionId' => $item['sectionId'],
                    'sectionName' => $item['sectionName'],
                    'questionId' => $item['questionId'],
                    'questionName' => $item['questionName'],
                    'questionType' => $item['questionType'],
                    'optionList' => $item['option'] ? json_decode($item['option'], true) : [],
                    'answerList' => $item['answer'] ? json_decode($item['answer'], true) : [],
                    'analysis' => $item['analysis'],
                    'userAnswerList' => []
                ];
                $answerList[] = $question;
            }

            $startResult = [
                'recordId' => $recordId,
                'courseName' => $course['name'],
                'answerDuration' => $course['answerDuration'],
                'listenFile' => $course['listenFile'],
                'answerList' => $answerList,
                'sectionList' => $courseSections
            ];
            // 提交事务
            Db::commit();
            return $startResult;
        }catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }

    }


    /**
     * 提交答案
     *
     * @param int|null $studentId 学生ID
     * @param int|null $trainerId 教练ID
     * @param array $submit 提交参数
     * @return int 记录ID
     */
    public function submitAnswer($studentId, $trainerId, $submit)
    {
        // 开启事务
        Db::startTrans();
        try {
            $recordId = $submit['recordId'] ?? null;
            if (empty($recordId)) {
                throw new ValidateException("测试记录不存在");
            }

            // 获取听力测试记录
            $LearnHearingRecordModel = new LearnHearingRecord();
            $learnHearingRecord = $LearnHearingRecordModel->getByIdAndAccount($recordId, $studentId, $trainerId);
            if (empty($learnHearingRecord)) {
                throw new ValidateException("测试记录不存在");
            }

            if ($learnHearingRecord['isSubmit']) {
                throw new ValidateException("测试已提交");
            }

            $answerList = $submit['answerList'] ?? [];

            // 准备提交题目
            $LearnHearingAnswerRecordModel = new LearnHearingAnswerRecord();
            $hearingAnswerRecordList = $LearnHearingAnswerRecordModel->getByRecordId($recordId);
            if (!$hearingAnswerRecordList) {
                throw new ValidateException("提交失败，当前测试无题目");
            }
//            halt($hearingAnswerRecordList);
            $updateHearingAnswerRecordList = [];
            foreach ($hearingAnswerRecordList as $it) {
                $result = null;
                if (!empty($answerList)) {
                    foreach ($answerList as $answer) {
                        if (isset($answer['id']) && $answer['id'] == $it['id']) {
                            $result = $answer;
                            break;
                        }
                    }
                }

                // 判断题目
                $isCorrect = false;
                $userAnswerList = [];
                if (!empty($result)) {
                    $questionType = $it['questionType'];
                    $userAnswerList = $result['userAnswerList'] ?? [];

                    // 移除空字符串
                    $userAnswerList = array_filter($userAnswerList, function($value) {
                        return !empty(trim($value));
                    });

                    switch ($questionType) {
                        case QuestionTypeEnum::E1: // 单选题
                            if (count($userAnswerList) == 1) {
                                $answerList = json_decode($it['answer'], true) ?: [];
                                $isCorrect = in_array($userAnswerList[0], $answerList);
                            }
                            break;
                        case QuestionTypeEnum::E2: // 多选题
                            if (!empty($userAnswerList)) {
                                $answerList = json_decode($it['answer'], true) ?: [];
                                // 检查用户答案是否包含所有正确答案
                                $isCorrect = !array_diff($answerList, $userAnswerList) && !empty($answerList);
                            }
                            break;
                    }
                }

                $updateHearingAnswerRecordList[] = [
                    'id' => $it['id'],
                    'isCorrect' => $isCorrect,
                    'userAnswer' => json_encode(array_values($userAnswerList), JSON_UNESCAPED_UNICODE)
                ];
            }
//            var_dump($learnHearingRecord['answerStartTime']);
            // 数据计算
            $nowTime = time();
            $answerStartTime = $learnHearingRecord['answerStartTime'];
            $useTime = $nowTime - strtotime($answerStartTime);

            $totalNum = count($updateHearingAnswerRecordList);
            $rightNum = 0;
            foreach ($updateHearingAnswerRecordList as $item) {
                if (!empty($item['isCorrect'])) {
                    $rightNum++;
                }
            }

            $errorNum = $totalNum - $rightNum;
            $correctRate = $totalNum > 0 ? intval(($rightNum * 100) / $totalNum) : 0;

            $learnHearingRecordUpdate = [
                'id' => $recordId,
                'totalNum' => $totalNum,
                'rightNum' => $rightNum,
                'errorNum' => $errorNum,
                'rightRate' => $correctRate,
                'answerEndTime' => date('Y-m-d H:i:s',$nowTime),
                'useTime' => $useTime,
                'isSubmit' => 1
            ];
//            halt($learnHearingRecordUpdate);
            // 修改数据
            $LearnHearingRecordModel->update($learnHearingRecordUpdate);

            // 修改答题结果
            foreach ($updateHearingAnswerRecordList as $item) {
                $LearnHearingAnswerRecordModel->update($item);
            }
            // 提交事务
            Db::commit();
            return $recordId;
        }catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }

    }

    /**
     * 记录详情
     *
     * @param int $recordId 记录ID
     * @return array 听力测试记录详情
     */
    public function getDetail($recordId)
    {
        $LearnHearingRecordModel = new LearnHearingRecord();
        // 获取听力测试记录详情（包含关联数据）
        $record = $LearnHearingRecordModel->find($recordId);

        if (empty($record)) {
            return null;
        }
        //获取听力答题记录
        $LearnHearingAnswerRecordModel = new LearnHearingAnswerRecord();
        $answerList = $LearnHearingAnswerRecordModel->where(['recordId'=>$recordId])->select();

        // 获取课程章节
        $CourseSectionModel = new CourseSection();
        $sectionList = $CourseSectionModel->listByCourse($record['courseId']);
        // 格式化为详情VO格式
        $detail = [
            'id' => $record['id'],
            'courseId' => $record['courseId'],
            'courseName' => $record['courseName'],
            'studentId' => $record['studentId'],
            'isSubmit' => $record['isSubmit'],
            'totalNum' => $record['totalNum'],
            'rightNum' => $record['rightNum'],
            'errorNum' => $record['errorNum'],
            'rightRate' => $record['rightRate'],
            'answerDuration' => $record['answerDuration'],
            'useTime' => $record['useTime'],
            'passRate' => $record['passRate'],
            'listenFile' => $record['listenFile'],
            'answerStartTime' => $record['answerStartTime'],
            'answerEndTime' => $record['answerEndTime'],
            // 可以添加更多需要的字段
            'answerList'=>$answerList,
            'sectionList'=>$sectionList
        ];

        return $detail;
    }
}
